JavaScript Comments

A comment is simply a line of text that is completely ignored by the JavaScript interpreter. Comments are usually added to provide extra information about the source code. It will not only help you understand your code when you look after some time but also others who are working with you on the same project.

Advantages of JavaScript Comments

  • To make code easy to understand: Comments help explain things so that anyone can follow along without getting confused.
  • To prevent code from running unnecessarily: Comments can stop certain parts of code from executing when you need to disable them temporarily.

Types of JavaScript Comments

Single-line Comment

It is represented by double forward slashes //. You can use single-line comments before or after a statement.

<!DOCTYPE html>
<html lang="en">
<body>
     <script>
        // This is a single-line comment before a statement
        let x = 10; // This is a single-line comment after a statement 
        // Write x to demo:
        document.getElementById("demo").innerHTML = x;
    </script>
</body>
</html>
                            
Multi-line Comment

It is represented by /* to open and */ to close. You can use multi-line comments for multiple lines of explanations.

<!DOCTYPE html>
<html lang="en">
<body>
    <script>
         /*
          This is a multi-line comment.
          It can span multiple lines to explain the code below.
         */
         let y = 20;
         document.getElementById("demo").innerHTML = y;
    </script>
</body>
</html>
                            
Output

Comments are ignored by the JavaScript interpreter, so they don't produce output. They are there to make your code more readable.